package com.lin.cloud.disk.controller;


import com.alipay.easysdk.factory.Factory;
import com.lin.cloud.disk.entity.request.CreateAliPayRequest;
import com.lin.cloud.disk.manage.IAlipayManageService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: cloud-disk
 * @description:
 * @author: Lin
 * @create: 2021-03-10 23:37
 **/
@RestController
@RequestMapping(value = "/api/alipay")
@Slf4j
@Api(tags = "支付控制器")
public class PayController {

    @Resource
    private IAlipayManageService alipayManageService;


    /**
     * app支付
     */
    @PostMapping("/app")
    public String app() {
        String subject = "测试支付";
        String total = "0.03";
        return alipayManageService.app(subject, total);
    }

    /**
     * 支付宝电脑网页支付
     */
    @PostMapping("/page")
    public String page(@RequestBody @Validated CreateAliPayRequest request) {
        return alipayManageService.page(request);
    }

    /**
     * 支付宝手机网页支付
     */
    @PostMapping("/wap")
    public String wap(@RequestBody @Validated CreateAliPayRequest request) {
        return alipayManageService.wap(request);
    }

    /**
     * 查询交易
     */
    @GetMapping("/getTrade/{outTradeNo}")
    public String getTrade(@PathVariable String outTradeNo) {
        return alipayManageService.getTrade(outTradeNo);
    }

    /**
     * 支付宝退款
     */
    @PostMapping("/refund")
    public String refund(String outTradeNo, String refundAmount) {
        return alipayManageService.refund(outTradeNo, refundAmount);
    }

    /**
     * 下载账单
     *
     */
    @PostMapping("/downloadBill")
    public String downloadBill(String billType, String billDate) {
        billType = "trade";
        billDate = "2020-11";
        return alipayManageService.downloadBill(billType, billDate);
    }


    @PostMapping("/notify")
    public void payNotice(HttpServletRequest request,HttpServletResponse response) throws Exception {
        log.info("=========支付宝异步回调========");
        if ("TRADE_SUCCESS".equals(request.getParameter("trade_status"))) {
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                log.info(name + " = " + request.getParameter(name));
            }
            // 支付宝验签
            if (Factory.Payment.Common().verifyNotify(params)) {
                alipayManageService.payNotice(params);
            }
        }
    }
}
